<?php
class Listing_Form_PostAnAddTranslateForm extends Ac_Form
{
    private $_category;
    private $_adid;
    private $_listing;
	private $_classname;
    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
     );

    protected $formDecorators = array(
           'PrepareElements',
            array('ViewScript', array('viewScript' => 'index/customization/translation.phtml'))
    );

    protected $subFormDecorators = array(
        'FormElements',
         array('Description', array('placement' => 'prepend')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );

    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    public function __construct($options = array())
    {
		$this->_classname = Model_Listing::getInstanceClassname((array)$_GET['category']);
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        parent::__construct();
    }
    
    public function init()
    {
        parent::init();

     
        $element = new Zend_Form_Element_Text('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
                'ViewHelper'
            )
        );
        
        $this->addElement($element);
		$classname = $this->_classname;
        $fl = $classname::getTranslationFormField();
//var_dump($fl, $classname);exit;	
		
		foreach($fl as $v => $r){
		if ($r == 'textarea') {
			$class = 'description textarea';
			if ($v == 'cs_en'){
				$id = 'counter_description';
				$desc = '<em>3000</em> characters remaining';
			} elseif ($v == 'rlj_en'){
				$id = 'counter_description2';
				$desc = '<em>3000</em> characters remaining';
			} elseif ($v == 'pe_en'){
				$id = 'counter_description3';
				$desc = '<em>3000</em> characters remaining';
			} else {
				$id = '';
				$desc = '';
			}
		} else {
			$class = 'title text';
			if ($v == 'tl_en'){
				$id = 'counter_title';
				$desc = '<em>100</em> characters remaining';
			}  elseif($v == 'cn_en'){
				$id = '';
				$desc = '';		
			} else {
				$id = '';
				$desc = '';
			}
		}
			$this->addElement($r, $v, array(
				'filters'    => array('StringTrim'),
				'description'=> $desc,
				'validators' => array(
					array('NotEmpty', true, array('messages' => 'This information is required')),                
				),
				'decorators' => array(
                            'ViewHelper',
                            'Errors',
							array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'id' => $id)),
							array('Label', array('placement' => 'prepend')),					
							array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => $class, 'openOnly'=>'true')),
				),
				'label'      => $v,
				//'attribs'    => array('style' =>'width:320px;float:left;'),
			));
			
			if ($v != 'cn_en') {
				$this->addElement('button', str_replace('en','tc', $v).'_back', array(
					'required'    => false,
					'ignore'      => true,
					'type'        => 'button',
					'label'       => 'Translate', 
					//'attribs'    => array('style' =>'left:332px;'),
					'decorators'  => $this->elementDecorators,
				));
			}
			
			$this->addElement($r, str_replace('en','tc', $v), array(
				'filters'    => array('StringTrim'),
				'validators' => array(
					array('NotEmpty', true, array('messages' => 'This information is required')),                
				),
				'decorators' => array(
                            'ViewHelper',
                            'Errors',
							array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => $class, 'closeOnly'=>'true')),
				),
				'label'      => $v,
				//'attribs'    => array('style' =>'width:320px;float:right;'),
				'value'      => $this->_listing->{$v} 
			));
		}
		
		if ($classname != 'Model_Listing_Job' && $classname != 'Model_Listing_Maid') {
			$this->addElement('textarea', 'st_en', array(
					'filters'    => array('StringTrim'),
					'validators' => array(
						array('NotEmpty', true, array('messages' => 'This information is required')),                
					),
					'decorators' => array(
								'ViewHelper',
								'Errors',
								array('Label', array('placement' => 'prepend')),
								array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'address textarea', 'openOnly'=>'true')),
					),
					'label'      => 'Street Address',
					//'attribs'    => array('style' =>'width:320px;float:left;'),
			));
			
			$this->addElement('textarea', 'st_tc', array(
					'filters'    => array('StringTrim'),
					//'description'=> "Addresses usually can't be directly translated. Please input the address in Chinese.",
					'validators' => array(
						array('NotEmpty', true, array('messages' => 'This information is required')),                
					),
					'decorators' => array(
								'ViewHelper',
								'Errors',
								//array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span')),
								array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'address textarea', 'closeOnly'=>'true')),
					),
					'label'      => 'Street Address',
					//'attribs'    => array('style' =>'width:320px;float:right;'),
			));
		}	
		$this->addElement('button', 'continue', array(
            'required'    => false,
            'ignore'      => true,
            'type'        => 'submit',
            'label'       => 'Continue',
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                             array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'button em')),
            ),
        ));
		
        $this->addElement('button', 'back', array(
            'required'    => false,
            'ignore'      => true,
			'type'        => 'submit',
            'label'       => 'Back', 
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                             array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')),
            ),
        ));


        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $this->getDecorator('ViewScript')->setOptions($opt);
    }

    public function populate(array $arr)
    {
		// print_r($this->_listing);
		// exit;
        
		$classname = Model_Listing::getInstanceClassname((array)$this->_listing->ca);
		$translateFields = $classname::getTranslationFormField();
				
		if (Zend_Registry::get('current_language') == 'en'){
			$ft = 'en';
			$tt = 'zh-TW';
			
			foreach($translateFields as $v => $r){
				if (empty($arr[$v])) {
					$this->getElement($v)->setValue($this->_listing->{$v});
				}
				if (empty($this->_listing->{str_replace('en','tc', $v)})) {
					if($v == 'tl_en'){
						$this->getElement(str_replace('en','tc', $v))->setValue($this->_listing->{$v});
					} else {
						$this->getElement(str_replace('en','tc', $v))->setValue(Ac_Translation::execute($this->_listing->{$v}, $tt, $ft));
					}
				} else {
					$this->getElement(str_replace('en','tc', $v))->setValue($this->_listing->{str_replace('en','tc', $v)});
				}
			}
			
			if ($classname != 'Model_Listing_Job' && $classname != 'Model_Listing_Maid') {
				$this->getElement('st_en')->setValue((string)$this->_listing->st_en);
				$this->getElement('st_tc')->setValue((string)$this->_listing->st_tc);			
			}
		} else {
			$ft = 'zh-TW';
			$tt = 'en';
			
			foreach($translateFields as $v => $r){
				if (empty($arr[$v])) {
					$this->getElement($v)->setValue($this->_listing->{str_replace('en','tc', $v)});
				}
				if (empty($this->_listing->{str_replace('en','tc', $v)})) {
					$this->getElement(str_replace('en','tc', $v))->setValue(Ac_Translation::execute($this->_listing->{str_replace('en','tc', $v)}, $tt, $ft));
				} else {
					$this->getElement(str_replace('en','tc', $v))->setValue($this->_listing->{$v});
				}
			}
			
			if ($classname != 'Model_Listing_Job' && $classname != 'Model_Listing_Maid') {
				$this->getElement('st_en')->setValue((string)$this->_listing->st_tc);
				$this->getElement('st_tc')->setValue((string)$this->_listing->st_en);
			}		
		}
		
		

        parent::populate($arr);
        return $arr;
    }

    public function save($preview = false)
    {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }
		
		$classname = Model_Listing::getInstanceClassname((array)$ad->ca);
		$translateFields = $classname::getTranslationFormField();
		
		if (Zend_Registry::get('current_language') == 'en'){
			$ad->ad_type = Model_Listing::ORIGINAL_LANGUAGE_EN;
			
			foreach($translateFields as $v => $r){
				$ad->{$v} = $this->getValue($v);
				$ad->{str_replace('en','tc', $v)} = $this->getValue(str_replace('en','tc', $v));
			}
			if ($classname != 'Model_Listing_Job' && $classname != 'Model_Listing_Maid') {
				$ad->st_en = $this->getValue('st_en');
				$ad->st_tc = $this->getValue('st_tc');
			}
		} else {
			$ad->ad_type = Model_Listing::ORIGINAL_LANGUAGE_TC;
			
			foreach($translateFields as $v => $r){
				$ad->{$v} = $this->getValue(str_replace('en','tc', $v));
				$ad->{str_replace('en','tc', $v)} = $this->getValue($v);
			}
			if ($classname != 'Model_Listing_Job' && $classname != 'Model_Listing_Maid') {	
				$ad->st_en = $this->getValue('st_tc');
				$ad->st_tc = $this->getValue('st_en');
			}
		}
		
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if(empty($ad->us)) {
                    $ad->user        = $user->_id;    
                }
            } else {
                $ad->user        = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }

		
        foreach ((array) $_REQUEST['category'] as $cat) {
            $tmp = new MongoId($cat);
            $ad->addCategory($tmp);
        }
        
        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));            
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->save();
            return $ad;
        }
        return $ad;
    }

    public function isValid($post = array())
    {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if ($match = Ac_Util::checkBadWord($_POST['title'])) {
            $this->getElement('title')->addError('Your Ad contains banned words: '. implode(', ', $match));
            $test2 = false;
        }

        //Check Bad Words in Description
        if ($match = Ac_Util::checkBadWord($_POST['description'])) {
            $this->getElement('description')->addError('Your Ad contains banned words: '. implode(', ', $match));
            $test2 = false;
        }

        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['title'])) {
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['description'])) {
            $test2 = false;
        }
        
        //Price
        if ($post['price'] == '1') {
            if (empty($post['price_text_value'])){
                $test2 = false;
            }
            elseif (!is_numeric($_POST['price_text_value'])) {
                $test2 = false;
            }
        }
        

        //Exception for Online Only for Area and District
        $data = Model_Location::one(array('_id' => new MongoId($post['area_l1'])));
        if (!empty($data)) {
            if ($data->nm_en != 'Online Only') {
                if (empty($post['area_l2'])) {
                    $this->getElement('area_l2')->addError('This information is required');
                    $test2 = false;
                }
            }
        }

        //Check the two validations
        if ($test1 & $test2){
            return true;
        }
        else {
            return false;
        }
    }

    protected function continueFillup()
    {

    }

    public function __toString()
    {
		if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }
		$translateFields = Model_Listing::getInstanceClassname((array)$ad->ca);
		$translateFields = $translateFields::getTranslationFormField();
		$str = '';
		foreach($translateFields as $v => $r){
			$str.= '
			$j("#'.str_replace('en','tc', $v).'_back").click(function(event) {
				$j.get("/listing/translator", { c: $j("#'.$v.'").val() },
                    function(data) {
						$j("#'.str_replace('en','tc', $v).'").attr("value",data);
				});
   
			});
			
			';
			
		}
			
	     
		$this->view->JQuery()->addJavascript($str);
        return parent::__toString();
    }
}
